﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;

namespace MTRC.ODMS.Web.SOM.Popup
{
    public partial class PopupPassengerFlowTemplate : BasePage_SOM
    {
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            this.ChangeLanguage += new ChangeLanguageEventHandler(SetLanguage_Click);
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                SetLanguage();
            }
        }

        void SetLanguage_Click(object sender, EventArgs e)
        {
            SetLanguage();   
        }

        private void SetLanguage()
        {
            this.PatronageExcelReport_Title.Text = this.GetLabel("SOM_PatronageExcelReport_Title");
            this.lblFileToBeUploaded.Text = this.GetLabel("SOM_PatronageExcelReport_FileToBeUploaded", true);
            this.btnUploadTemplate.Text = this.GetLabel("Upload");
            this.btnClose.Text = this.GetLabel("CloseWindow");
        }

        /// <summary>
        /// Upload empty template
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnUploadTemplate_Click(object sender, EventArgs e)
        {
            string fileName = APJ.Util.Utility.GetAppSetting("SOM_DailyPatronageReport_ExcelName");
            bool hasERROR = false;

            //check the file if null 
            if (this.txtfileUpload.PostedFile.ContentLength <= 0)
            {
                this.PAlert(this.GetMessage("SOM_FilePathNull"));
                return;
            }

            //Check file type
            string fileType = string.Empty;
            fileType = this.txtfileUpload.PostedFile.FileName.Substring(this.txtfileUpload.PostedFile.FileName.LastIndexOf(".") + 1);
            if (fileType.ToLower() != ("xlsx").ToLower())
            {
                this.Alert(this.GetMessage("SOM_FileTypeError"));
                return;
            }

            //Save Temp file
            string tempFilePath = APJ.Util.Utility.GetAppSetting("SOM_DailyPatronageReport_UploadTempFilePath");
            string fullFileTempName = APJ.Util.Utility.GetAppSetting("SOM_DailyPatronageReport_UploadTempFilePath") + fileName;
            string PassengerFlowSheet = APJ.Util.Utility.GetAppSetting("SOM_DailyPatronageReport_PassengerFlowSheet");
            string RawDataInputbyStationSheet = APJ.Util.Utility.GetAppSetting("SOM_DailyPatronageReport_RawDataInputbyStationSheet");


            if (!Directory.Exists(tempFilePath))
            {
                Directory.CreateDirectory(tempFilePath);
            }

            this.txtfileUpload.PostedFile.SaveAs(Path.Combine(tempFilePath, fullFileTempName));


            //Check file sheet
            using (SpreadsheetDocument document = SpreadsheetDocument.Open(fullFileTempName, true, new OpenSettings() { AutoSave = true }))
            {
                bool ExistPassengerFlow = false;
                bool ExistRawDataInputbyStation = false;
                IEnumerable<Sheet> sheets = document.WorkbookPart.Workbook.Descendants<Sheet>();
                foreach (var sheet in sheets)
                {
                    if (sheet.Name == PassengerFlowSheet)
                    {
                        ExistPassengerFlow = true;
                    }
                    if (sheet.Name == RawDataInputbyStationSheet)
                    {
                        ExistRawDataInputbyStation = true;
                    }
                }

                if (ExistPassengerFlow && ExistRawDataInputbyStation)
                {
                    hasERROR = false;
                }
                else
                {
                    hasERROR = true;
                    if (!ExistPassengerFlow && !ExistRawDataInputbyStation)
                    {
                        
                        this.Alert(this.GetMessage("SOM_PatronageExcelReport_NotFindSheetName") + ": '" + PassengerFlowSheet + "' and '" + RawDataInputbyStationSheet + "'");
                        //this.Alert(this.GetMessage("SOM_PatronageExcelReport_NotFindSheetName") + ": \\\"" + PassengerFlowSheet + "\\\" and \\\"" + RawDataInputbyStationSheet + "\\\"");
                        return;
                    }
                    if (!ExistPassengerFlow)
                    {
                        this.Alert(this.GetMessage("SOM_PatronageExcelReport_NotFindSheetName") + ": '" + PassengerFlowSheet + "'");
                        //this.Alert(this.GetMessage("SOM_PatronageExcelReport_NotFindSheetName") + ": \\\"" + PassengerFlowSheet + "\\\"");
                        return;
                    }
                    if (!ExistRawDataInputbyStation)
                    {
                        this.Alert(this.GetMessage("SOM_PatronageExcelReport_NotFindSheetName") + ": '" + RawDataInputbyStationSheet + "'");
                        //this.Alert(this.GetMessage("SOM_PatronageExcelReport_NotFindSheetName") + ": \\\"" + RawDataInputbyStationSheet + "\\\"");
                        return;
                    }
                    return;
                }
            }

            //Upload to SOM_DailyPatronageReportFilePath
            string filePath = APJ.Util.Utility.GetAppSetting("SOM_DailyPatronageReport_UploadFilePath");
            if (!Directory.Exists(filePath))
            {
                Directory.CreateDirectory(filePath);
            }

            //add by jack 20151008 for u182
            string fileBackPath = APJ.Util.Utility.GetAppSetting("SOM_DailyPatronageReport_UploadBackFilePath"); 
            if (!Directory.Exists(fileBackPath))
            {
                Directory.CreateDirectory(fileBackPath);
            }

            string fullFileName = APJ.Util.Utility.GetAppSetting("SOM_DailyPatronageReport_UploadFilePath") + fileName;
            this.txtfileUpload.PostedFile.SaveAs(Path.Combine(filePath, fullFileName));
            string timeStampfileName = "DailyPatronageReport_" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xlsx";
            //add by jack 20151008 for u182
            //string fullTimeFileName = APJ.Util.Utility.GetAppSetting("SOM_DailyPatronageReport_UploadFilePath") + timeStampfileName;
            //this.txtfileUpload.PostedFile.SaveAs(Path.Combine(filePath, fullTimeFileName));
            string fullTimeFileName = APJ.Util.Utility.GetAppSetting("SOM_DailyPatronageReport_UploadBackFilePath") + timeStampfileName;
            this.txtfileUpload.PostedFile.SaveAs(Path.Combine(fileBackPath, fullTimeFileName)); //add by jack 20151008 for u182

            //delete temp file 
            if (File.Exists(fullFileTempName))
            {
                File.Delete(fullFileTempName);
            }
            this.Alert(this.GetMessage("SOM_PatronageExcelReport_UploadSuccess"));
        }

        /// <summary>
        /// Down load empty template
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnDownloadTemplate_Click(object sender, EventArgs e)
        {
            string fileName = APJ.Util.Utility.GetAppSetting("SOM_DailyPatronageReport_ExcelName");
            string fullFileName = APJ.Util.Utility.GetAppSetting("SOM_DailyPatronageReport_UploadFilePath") + fileName;
            if (File.Exists(fullFileName))
            {
                try
                {
                    string filename = Path.GetFileName(fullFileName);
                    Response.Clear();
                    Response.ContentType = "application/octet-stream ";
                    Response.AppendHeader("Content-Disposition ", "attachment; Filename = " + System.Convert.ToChar(34) + filename + System.Convert.ToChar(34));
                    Response.Charset = " ";
                    Response.ContentEncoding = System.Text.Encoding.Unicode;
                    Response.Flush();
                    Response.WriteFile(fullFileName);
                }
                catch (Exception ex)
                {
                    this.Alert(ex.Message);
                }
            }
            else
            {
                this.Alert(this.GetMessage("SOM_PatronageExcelReport_NofindTemplate"));
            }

        }

        protected void btnClose_Click(object sender, EventArgs e) { 
        
        }
        
    }
}